//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';
import goodsItem from '../comm/goodsItem.vue';
import cSort from '../comm/sort.vue';
import BScroll from "better-scroll";
import { scrollMixin } from "../../../utils/mixin";
export default {
  name:'',
  //import引入的组件需要注入到对象中才能使用
  components: {
    goodsItem,
    cSort
  },
  mixins: [scrollMixin], //加载更多
  data() {
    return {
      value:'',
      pluginType:'collection-center',
      isLoadMore: true,
      total_page: 0,
      query:{
        parent_id:'', //一级分类id（不传就返回一级分类）
        is_home:'',
      },
      params:{
        search:{
          keyword:'',
          parentid:'',
          childid:'',
        },
        order_field:'',
        order_by:'',
        page: 1
      },
      storeScroll: "",
      classifyScroll: "",
      classifyIndex:0,
      activeName:[],
      classifyArr:[],
      showTitle:[],
      secondaryId:'',
      secondArr:[
        {
          id:'',
          name:'全部'
        }
      ],
      classifyList:[]
    };
  },
  //监听属性 类似于data概念
  computed: {},
  //监控data中的数据变化
  watch: {
  },
  //方法集合
  methods: {
    goodsNav() {
      this.$router.push(this.fun.getUrl('collectionUser', {}, {}));
    },
    sortOut(e) {
      if (this.classifyList.length == 0) {
        return;
      }
      this.params.page = 1;
      this.params.order_field = e.order_field;
      this.params.order_by = e.order_by;
      this.categoryData();
    },
    letterOn() { //推荐分类
      this.secondArr = [
        {
          id:'',
          name:'全部'
        }
      ];
      this.showTitle = [];
      this.classifyIndex = -1;
      this.query.parent_id = '';
      this.query.is_home = 1;
      this.params.search.parentid = '';
      this.params.search.childid = '';
      this.secondaryId = '';
      if (this.storeScroll) {
        this.storeScroll.scrollTo(0, 0);
      }
      this.category2();
      this.categoryData();
    },
    chooseSecondary(id,level) { //二级分类
      this.activeName = [];
      if(level == 1) {
        this.params.search.parentid = id;
        this.params.search.childid = '';
      } else {
        this.params.search.parentid = '';
        this.params.search.childid = id;
      }
      this.secondaryId = id;
      this.params.page = 1;
      if (this.storeScroll) {
        this.storeScroll.scrollTo(0, 0);
      }
      this.showTitle = this.secondArr;
      this.categoryData();
    },
    maskChange() {
      this.activeName = [];
    },
    classifyOnText(index,id) { //切换分类
      this.classifyIndex = index;
      this.params.search.parentid = id;
      this.query.parent_id = id;
      this.params.page = 1;
      this.query.is_home = 0;
      this.params.search.childid = '';
      this.secondArr = [
        {
          id:'',
          name:'全部'
        }
      ];
      this.showTitle = [];
      this.secondaryId = '';
      if (this.storeScroll) {
        this.storeScroll.scrollTo(0, 0);
      }
      this.category2();
      this.categoryData();
    },
    initData() {
      this.params.page = 1;
      this.query.parent_id = '';
      this.params.search.parentid = '';
      this.params.search.childid = '';
      this.query.parentid = '';
      this.classifyIndex = 0;
      this.query.is_home = 0;
      this.classifyArr = [];
      this.secondArr = [
        {
          id:'',
          name:'全部'
        }
      ];
    },
    category() {
      //会员信息
      $http
        .post("plugin.collection-center.frontend.controllers.goods.category.index", this.query, "loading")
        .then(res => {
          if (res.result === 1) {
            let data = res.data;
            this.classifyArr = data.category_list;
            if(this.classifyArr) {
              this.params.search.parentid = data.category_list[0].id;
              this.query.parent_id = data.category_list[0].id;
              this.categoryData();
              this.category2();
            }
          } else {
            this.$dialog.alert({
              message: res.msg
            });
          }
        })
        .catch(err => {
          console.log("getUserData::err", err);
        });
    },
    category2() {
      $http
        .post("plugin.collection-center.frontend.controllers.goods.category.index", this.query, "loading")
        .then(res => {
          if (res.result === 1) {
            let data = res.data;
            let list = data.category_list;
            this.secondArr = [...this.secondArr,...list];
            this.showTitle = this.secondArr;
          } else {
            this.$dialog.alert({
              message: res.msg
            });
          }
        })
        .catch(err => {
          console.log("getUserData::err", err);
        });
    },
    titleChange(arr) { //折叠面板
      arr[0] == 1?this.showTitle =[]:this.showTitle = this.secondArr;
    },
    categoryData() {
      $http
        .post("plugin.collection-center.frontend.controllers.goods.goods.index", this.params, "loading")
        .then(res => {
          if (res.result === 1) {
            let data = res.data;
            let list = data.goods_list.data;
            this.isLoadMore = true;
            this.total_page = data.goods_list.last_page;
            if (!this.total_page) {
              this.params.page = 0;
            }
            this.classifyList = list;
            this.$nextTick(() => {
              if(this.classifyList.length > 0) {
                this.debounce();
              }
            });
          } else {
            this.$dialog.alert({
              message: res.msg
            });
          }
        })
        .catch(err => {
          console.log("getUserData::err", err);
        });
    },
    getMoreData() {
      this.isLoadMore = false; // 防止多次请求分页数据
      if (this.params.page >= this.total_page) {
        return;
      } else {
        this.params.page = this.params.page + 1;
        $http.post("plugin.collection-center.frontend.controllers.goods.goods.index", this.params, "加载中").then(
          res => {
            this.isLoadMore = true;
            if (res.result === 1) {
              let classifyList = res.data.goods_list?.data;
              this.classifyList = [...this.classifyList, ...classifyList]; //数组拼接
            } else {
              this.params.page = this.params.page - 1;
              this.isLoadMore = false;
            }
          },
          function(response) {
            console.log("response", response);
            // error callback
          }
        );
      }
    },
    debounce() {
      // clearTimeout方法，以便控制连续触发带来的无用调用
      if (this.debounce_timer) {
        clearTimeout(this.debounce_timer); // 先清除之前的延时，并在下面重新开始计算时间
      }
      this.debounce_timer = setTimeout(() => {
        // 800毫秒以后执行方法
        this._initScrollList();
      }, 800); // 如果还没有执行就又被触发，会根据上面的clearTimeout来清除并重新开始计算
    },
    searchTo() {
      this.$router.push(this.fun.getUrl("search", { fromHome: 1},{plugin_type:'collection-center'}));
    },
    _initScrollList() {
      if (this.classifyList.length > 0) {
        this.storeScroll = new BScroll(this.$refs.handpickList, {
          click: true,
          scrollY: true,
          probeType: 3,
          swipeBounceTime: 500,
          useTransition: false,
          mouseWheel: true
        });
      } else {
        this.storeScroll.refresh();
      }
      let loadMore = document.getElementById("loadMore");
      this.storeScroll.on("scroll", pos => {
        if (loadMore?.offsetTop > this.$refs.handpickList?.offsetHeight && loadMore?.offsetTop + pos.y < this.$refs?.handpickList.offsetHeight && this.isLoadMore) {
          this.getMoreData();
          console.log("分类加载更多");
          setTimeout(() => {
            this.storeScroll.refresh();
          }, 800);
        }
      });
      this.$once("hook:beforeDestroy", () => {
        console.log('是否执行');
        window.removeEventListener("scroll", this.storeScroll);
      });
    }
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {
  
  },
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
  },
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {
    this.initData();
    this.category();
  }, //如果页面有keep-alive缓存功能，这个函数会触发
}